//
//  StatusListViewModel.swift
//  weibo
//
//  Created by 陈伟 on 15/10/19.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import Foundation
import SDWebImage

class StatusListViewModel {
    
    lazy var dataList = [StatusViewModel]()
    //加载网络数据
    func loadStatusData(ispullup ispullup: Bool, finished: (isSuccess: Bool)->()) {

        let since_id: Int = ispullup ? 0 : (dataList.first?.status.id ?? 0)
        let max_id: Int = ispullup ? (dataList.last?.status.id ?? 0) : 0
//                let since_id: Int = 0
//                let max_id: Int = 0
        
        NetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id){ (result, error) -> () in
            if error != nil {
                print("数据加载失败，请重试")
                finished(isSuccess: false)
                return
            }
            //            print(result)
            guard let statusData = result?["statuses"] as?  [[String: AnyObject]] else {
                print("数据错误")
                finished(isSuccess: false)
                return
            }
//                        print(statusData)
            var tempArray = [StatusViewModel]()
            
            for dict in statusData {
                let statusModel = StatusViewModel(status: Status(dict: dict))
                tempArray.append(statusModel)
            }
            if max_id > 0 {
                self.dataList += tempArray
            }else{
                
                self.dataList = tempArray + self.dataList
            }
//            finished(isSuccess: true)
            print(self.dataList.count)
            self.cacheSingleImage(tempArray, finished: finished)
            //print(self.dataList)
        }
    }
    
    private func cacheSingleImage(dataList: [StatusViewModel], finished: (isSuccess: Bool) -> ()){
        
        let group = dispatch_group_create()
        
        for vm in dataList {
            
            if vm.thumbnailUrls?.count != 1 {
                continue
            }
            let url = vm.thumbnailUrls?.first
            dispatch_group_enter(group)
            
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached], progress: nil, completed: { (image, _, _, _, _) -> Void in
                
//                if let img = image, let data = UIImagePNGRepresentation(img) {
                dispatch_group_leave(group)
            })
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(isSuccess: true)
        }
    }
}

